<template>
  <view class="container">
    <!-- 佣金总览 -->
    <view class="commission-overview">
      <view class="overview-header">
        <text class="title">我的推广</text>
        <text class="total-amount">¥{{ commissionInfo.total.toFixed(2) }}</text>
      </view>

    </view>

    <!-- 推广记录 -->
    <uni-section title="推广记录" type="line">
      <view class="records-list">
        <view
          v-for="(record, index) in promotionRecords"
          :key="record.id"
          class="record-item"
        >
          <view class="record-header">
            <view class="record-info">
              <text class="product-name">订单佣金</text>
              <text class="order-time">
                {{ formatTime(record.createTime) }}
              </text>
            </view>
            <text class="commission-amount">
              +¥{{ formatAmount(record.salesCommission) }}
            </text>
          </view>

          <view class="record-details">
            <view class="detail-item">
              <text class="detail-label">订单号：</text>
              <text class="detail-value">{{ record.orderNumber }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">购买用户：</text>
              <text class="detail-value">{{ record.customerUserName }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">订单金额：</text>
              <text class="detail-value"
                >¥{{ formatAmount(record.sellingPrice) }}</text
              >
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view
        v-if="loading && promotionRecords.length === 0"
        class="loading-state"
      >
        <uni-load-more
          status="loading"
          :content-text="{
            contentdown: '',
            contentrefresh: '正在加载...',
            contentnomore: ''
          }"
        />
      </view>

      <!-- 空状态 -->
      <view v-if="isEmpty && !loading" class="empty-state">
        <image
          class="empty-icon"
          src="/static/icons/empty.png"
          mode="aspectFit"
        />
        <text class="empty-text">暂无推广记录</text>
        <text class="empty-desc">分享商品链接给好友，获得佣金奖励</text>
      </view>

      <!-- 底部加载提示 -->
      <view v-if="promotionRecords.length > 0" class="load-more">
        <uni-load-more
          :status="loading ? 'loading' : hasMore ? 'more' : 'noMore'"
          :content-text="{
            contentdown: '上拉查看更多',
            contentrefresh: '正在加载...',
            contentnomore: '已加载全部数据',
          }"
          @clickLoadMore="onReachBottom"
        />
      </view>
    </uni-section>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import request from '@/utils/request';

// 推广记录接口数据类型
interface PromotionRecord {
  id: number;
  orderNumber: string; // 订单编号
  customerUserName: string; // 姓名
  sellingPrice: number; // 商品售价（分）
  salesCommission: number; // 佣金价格（分）
  createTime: string; // 创建时间
}

// 分页参数
const pageParams = ref({
  pageNum: 1,
  pageSize: 10,
});

// 数据状态
const promotionRecords = ref<PromotionRecord[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const isEmpty = ref(false);

// 佣金信息
const commissionInfo = ref({
  total: 0,
  available: 0,
  frozen: 0,
  totalWithdraw: 0,
});

// 格式化金额（分转元）
const formatAmount = (amount: number) => {
  return (amount / 100).toFixed(2);
};

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 获取推广记录
const getPromotionRecords = async (isLoadMore = false) => {
  if (loading.value || (!hasMore.value && isLoadMore)) {
    return;
  }

  loading.value = true;

  try {
    const response = await request<{
      rows: PromotionRecord[];
      total: number;
      code: number;
      msg: string;
    }>({
      url: '/order/commission/orders',
      method: 'GET',
      data: {
        pageNum: pageParams.value.pageNum,
        pageSize: pageParams.value.pageSize,
      },
    });

    const { rows, total } = response;

    // 确保rows是数组
    const recordsList = Array.isArray(rows) ? rows : [];

    if (isLoadMore) {
      promotionRecords.value = [...promotionRecords.value, ...recordsList];
    } else {
      promotionRecords.value = recordsList;
    }

    // 检查是否还有更多数据 - 基于已加载数量和总数量判断
    hasMore.value = promotionRecords.value.length < (total || 0);
    isEmpty.value = promotionRecords.value.length === 0;

    // 如果是加载更多且还有数据，页码+1
    if (isLoadMore && recordsList.length > 0) {
      pageParams.value.pageNum++;
    }
  } catch (error) {
    console.error('获取推广记录失败:', error);
    if (!isLoadMore) {
      isEmpty.value = true;
    }
  } finally {
    loading.value = false;
  }
};

// 下拉刷新
const onRefresh = async () => {
  pageParams.value.pageNum = 1;
  hasMore.value = true;
  // 刷新时同时更新佣金总额和推广记录
  await Promise.all([getCommissionTotal(), getPromotionRecords(false)]);
};

// 滚动到底部加载更多
const onReachBottom = async () => {
  if (hasMore.value && !loading.value) {
    pageParams.value.pageNum++;
    await getPromotionRecords(true);
  }
};

// 获取佣金总额
const getCommissionTotal = async () => {
  try {
    const response: any = await request({
      url: '/order/commission',
      method: 'GET',
    });

    if (
      response.code === 200 &&
      response.data !== null &&
      response.data !== undefined
    ) {
      // 将响应数据除以1000并保留两位小数（参考个人中心页面的处理方式）
      const commissionAmount = Number(response.data) / 100;
      commissionInfo.value.total = Number(commissionAmount.toFixed(2));
    } else {
      commissionInfo.value.total = 0;
    }
  } catch (error) {
    console.error('获取佣金总额失败:', error);
    commissionInfo.value.total = 0;
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    pending: '待结算',
    settled: '已结算',
    cancelled: '已取消',
  };
  return statusMap[status] || '未知状态';
};

// 获取状态样式类
const getStatusClass = (status: string) => {
  const classMap: { [key: string]: string } = {
    pending: 'status-pending',
    settled: 'status-settled',
    cancelled: 'status-cancelled',
  };
  return classMap[status] || '';
};

// 页面生命周期
onMounted(async () => {
  // 同时获取佣金总额和推广记录
  await Promise.all([getCommissionTotal(), getPromotionRecords()]);
});

onUnmounted(() => {
  // 清理工作
});

// uni-app页面生命周期函数
// 触底事件
const onReachBottomHandler = () => {
  onReachBottom();
};

// 下拉刷新事件
const onPullDownRefreshHandler = async () => {
  await onRefresh();
  uni.stopPullDownRefresh();
};

// 暴露给uni-app的页面实例
const instance = getCurrentInstance();
if (instance) {
  instance.proxy.onReachBottom = onReachBottomHandler;
  instance.proxy.onPullDownRefresh = onPullDownRefreshHandler;
}
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.commission-overview {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx;
  color: #fff;
  border-top: 1rpx solid #fff;
}

.overview-header {
  text-align: center;
  /* margin-bottom: 40rpx; */
}

.overview-header .title {
  font-size: 32rpx;
  display: block;
  margin-bottom: 20rpx;
  opacity: 0.9;
}

.overview-header .total-amount {
  font-size: 60rpx;
  font-weight: bold;
  display: block;
}

.overview-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  opacity: 0.8;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.section-icon {
  width: 40rpx;
  height: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.records-list {
  background-color: #fff;
  padding: 0 30rpx;
}

.record-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.record-info {
  flex: 1;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
  line-height: 1.4;
  margin-bottom: 10rpx;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.commission-amount {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}

.record-details {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 10rpx;
}

.detail-item {
  display: flex;
  margin-bottom: 10rpx;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-size: 24rpx;
  color: #666;
  width: 140rpx;
  flex-shrink: 0;
}

.detail-value {
  font-size: 24rpx;
  color: #333;
  flex: 1;
}

.status-pending {
  color: #ffc107;
}

.status-settled {
  color: #28a745;
}

.status-cancelled {
  color: #dc3545;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 30rpx;
  background-color: #fff;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #ccc;
  text-align: center;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 30rpx;
  background-color: #fff;
}

.load-more {
  background-color: #fff;
  padding: 20rpx 0;
}
</style>
